import random

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

import constants
from meiduo_mall.libs.captcha.captcha import captcha
# from meiduo_mall.libs.yuntongxun.sms import CCP
from users.models import Users
from verifications import serializers
from celery_tasks.sms.tasks import send_sms_code

class ImageCodeView(APIView):
    def get(self,request,image_code_id):
        print('进入视图')
        text,image = captcha.generate_captcha()
        print(text)
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex('img_%s' % image_code_id,constants.IMAGE_CODES_REDIS_EXPIRES,text)
        return HttpResponse(image,content_type='image/jpg')

class SMSCodeView(GenericAPIView):
    serializer_class = serializers.ImageCodeCheckSerializer
    def get(self,request,mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid()
        """
        1.获取参数
        2.校验参数
        3.生成验证码及保存在redis
        4.发送验证码
        5.返回数据
        """
        sms_code = '%06d'% random.randint(0,999999)


        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex('sms_%s'% mobile,constants.IMAGE_CODES_REDIS_EXPIRES,sms_code)
        pl.setex('send_flag%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()
        expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)

        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)
        send_sms_code.delay(mobile, sms_code, expires)
        print(sms_code)
        request.user
        return Response({"message": "OK"})

class UserCountView(APIView):
    def get(self,reqiest,username):
        count = Users.objects.filter(username=username).count()
        data = {
            'username':username,
            'count':count
        }
        return Response(data)







